<template>
  <view class="profile-page">
    <!-- 顶部导航栏占位 -->
    <view class="navbar-placeholder"></view>

    <view class="content">
      <!-- 头像区域 -->
      <view class="avatar-section">
        <image class="avatar" src="/static/images/avatar.png" mode="aspectFill" />
      </view>

      <!-- 基本信息列表 -->
      <view class="info-list">
        <!-- 会员信息卡片 -->
        <view class="info-card">
          <view class="card-title">会员信息</view>
          <view class="info-item">
            <text class="label">会员等级</text>
            <text class="value-text highlight">{{ customerInfo.memberName || '普通会员' }}</text>
          </view>
          <view class="info-item">
            <text class="label">会员号</text>
            <text class="value-text">{{ customerInfo.memberCode || '暂无' }}</text>
          </view>
          <view class="info-item">
            <text class="label">总充值金额</text>
            <text class="value-text highlight">¥{{ customerInfo.totalAmount || '0.00' }}</text>
          </view>
        </view>

        <!-- 个人信息卡片 -->
        <view class="info-card">
          <view class="card-title">个人信息</view>
          <view class="info-item">
            <text class="label">昵称</text>
            <input class="value-input" type="text" v-model="customerInfo.uName" placeholder="请输入昵称" />
          </view>
          <view class="info-item">
            <text class="label">手机号</text>
            <view class="phone-display" @tap="togglePhoneDisplay">
              <text class="value-text">{{ displayPhone }}</text>
              <text class="view-hint">{{ isPhoneMasked ? '点击查看' : '点击隐藏' }}</text>
            </view>
          </view>
          <view class="info-item">
            <text class="label">注册时间</text>
            <text class="value-text">{{ formatDate(customerInfo.createAt) }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮区域 -->
      <view class="action-section">
        <button class="action-btn" @tap="showChangePasswordModal">修改密码</button>
        <button class="save-button" @tap="saveProfile">保存修改</button>
        <button class="logout-btn" @tap="handleLogout">退出登录</button>
      </view>
    </view>

    <!-- 修改密码弹窗 -->
    <view v-if="showPasswordModal" class="popup-mask" @tap="closePasswordModal">
      <view class="password-modal" @tap.stop>
        <view class="modal-title">修改密码</view>
        <view class="input-group">
          <input type="password" v-model="passwordForm.oldPassword" placeholder="请输入原密码" />
          <input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码" />
          <input type="password" v-model="passwordForm.confirmPassword" placeholder="请确认新密码" />
        </view>
        <view class="modal-buttons">
          <button class="cancel-btn" @tap="closePasswordModal">取消</button>
          <button class="confirm-btn" @tap="changePassword">确认修改</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { customerApi, userApi } from '../../api'

// 顾客信息
const customerInfo = ref({
  customerId: null,
  uName: null,
  phone: null,
  pwd: null,
  createAt: null,
  customerFullName: null,
  memberCode: null,
  point: 0,
  surplus: 0,
  totalAmount: 0,
  memberId: null,
  memberName: null,
  needAmount: 0,
  giftPoint: 0,
})

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 控制弹窗显示
const showPasswordModal = ref(false)

// 控制手机号显示状态
const isPhoneMasked = ref(true)

// 格式化手机号显示
const displayPhone = computed(() => {
  if (!customerInfo.value.phone) return '暂无'
  if (isPhoneMasked.value) {
    return customerInfo.value.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  return customerInfo.value.phone
})

// 切换手机号显示状态
const togglePhoneDisplay = () => {
  isPhoneMasked.value = !isPhoneMasked.value
}

// 格式化日期
const formatDate = (date) => {
  console.log(date)
  if (!date) return '无'
  // 将日期字符串中的空格替换为T，使其符合ISO格式
  const isoDate = date.replace(' ', 'T')
  const dateObj = new Date(isoDate)
  
  // 检查日期是否有效
  if (isNaN(dateObj.getTime())) {
    return '暂无'
  }

  // 格式化日期
  const year = dateObj.getFullYear()
  const month = String(dateObj.getMonth() + 1).padStart(2, '0')
  const day = String(dateObj.getDate()).padStart(2, '0')
  const hours = String(dateObj.getHours()).padStart(2, '0')
  const minutes = String(dateObj.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 显示修改密码弹窗
const showChangePasswordModal = () => {
  showPasswordModal.value = true
}

// 关闭修改密码弹窗
const closePasswordModal = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  showPasswordModal.value = false
}

// 修改密码
const changePassword = async () => {
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword || !passwordForm.value.confirmPassword) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    uni.showToast({
      title: '两次输入的新密码不一致',
      icon: 'none'
    })
    return
  }
  // 验证原密码
  const uId = uni.getStorageSync('token')
  const data = {
    uId:uId,
    pwd:passwordForm.value.oldPassword
  }
  console.log(data)
  const res = await userApi.verifyOldPassword(data)
  if (res.code != 200) {
    uni.showToast({
      title: res.msg || '修改失败',
      icon: 'none'
    })
    return
  } 
  // 修改密码
  data.pwd = passwordForm.value.newPassword
  console.log("修改密码:"+data.pwd)
  const result = await userApi.changePassword(data)
  if (result.code != 200) {
    uni.showToast({
      title: result.msg || '修改失败',
      icon: 'none'
    })
  }else{
    uni.showToast({
      title: '修改成功，请重新登录',
      icon: 'success'
    })
    closePasswordModal()
    // 延迟1秒后执行退出登录
    setTimeout(() => {
      logout()
    }, 1000)
  }
  
  
}

// 保存个人信息
const saveProfile = async () => {
// TODO: 实现更新用户信息的接口调用
const user = {
    uId:uni.getStorageSync('token'),
    uName:customerInfo.value.uName
  }
  console.log(user)
  const res = await userApi.updateUserInfo(user)
  if (res.code === 200) {
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
  } else {
    uni.showToast({
      title: res.msg || '保存失败',
      icon: 'none'
    })
  }
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        logout()
      }
    }
  })
}

const logout = () => {
  // 清除token
  uni.removeStorageSync('token')
  // 清除用户信息
  uni.removeStorageSync('userInfo')
  // 跳转到首页
  uni.reLaunch({
     url: '../home/index'
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // TODO: 调用获取用户信息接口
    const uId = uni.getStorageSync('token')
    const res = await customerApi.getCustomerInfo(uId)
    if (res.code === 200) {
      customerInfo.value = res.data
      console.log(customerInfo.value)
    } else {
      uni.showToast({
        title: res.msg || '获取信息失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取信息失败',
      icon: 'none'
    })
  }
}


// 更新密码（预留接口）
const updatePassword = async (newPassword) => {
  // TODO: 实现更新密码的接口调用
  return { code: 200, msg: 'success' } // 测试数据
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.navbar-placeholder {
  height: 44px;
}

.content {
  padding: 0 32rpx;
}

.avatar-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40rpx;
  margin-bottom: 40rpx;

  .avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    border: 4rpx solid #fff;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-bottom: 40rpx;
}

.info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .card-title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    padding-left: 16rpx;
    border-left: 4rpx solid #1e90ff;
  }
}

.info-item {
  display: flex;
  align-items: center;
  padding: 20rpx 16rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  .label {
    font-size: 28rpx;
    color: #666;
    width: 160rpx;
    flex-shrink: 0;
  }

  .value-input,
  .value-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .value-input {
    border: none;
    outline: none;
    padding: 0;
    background: transparent;
  }

  .highlight {
    color: #1e90ff;
    font-weight: 500;
  }
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-bottom: 40rpx;
}

.action-btn,
.save-button {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  font-size: 32rpx;
  background: #1e90ff;
  color: #fff;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(30, 144, 255, 0.2);
}

.logout-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  font-size: 32rpx;
  background: #ff4d4f;
  color: #fff;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.2);
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.password-modal {
  background: #fff;
  border-radius: 16rpx;
  width: 600rpx;
  padding: 32rpx;
  z-index: 1000;
  box-sizing: border-box;

  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
    text-align: center;
    margin-bottom: 32rpx;
  }

  .input-group {
    margin-bottom: 32rpx;
    width: 100%;
    box-sizing: border-box;

    input {
      width: 100%;
      height: 88rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 0 24rpx;
      margin-bottom: 24rpx;
      font-size: 28rpx;
      background: #fff;
      box-sizing: border-box;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .modal-buttons {
    display: flex;
    justify-content: space-between;
    gap: 24rpx;
    width: 100%;
    box-sizing: border-box;

    button {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      border-radius: 8rpx;
      font-size: 28rpx;
      margin: 0;
      padding: 0;
    }

    .cancel-btn {
      background: #f5f5f5;
      color: #666;
    }

    .confirm-btn {
      background: #1e90ff;
      color: #fff;
    }
  }
}

.phone-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .value-text {
    font-size: 28rpx;
    color: #333;
  }

  .view-hint {
    font-size: 24rpx;
    color: #1e90ff;
    margin-left: 16rpx;
  }
}
</style> 